import { observable, computed, action } from 'mobx';
import { Promise } from 'drunk-base';
import * as moment from 'moment';

export interface IPageMetaData {
    current: number;  // 当前页数
    pageSize: number;  // 每页条数
    total: number;  // 数据总数
    totalPages: number;  // 总页数
}

export abstract class ListModel<T> {

    @observable data: T[];
    @observable meta: IPageMetaData = {} as any;
    @observable loading: boolean;

    @observable searchName: string;

    searchTimes: [number, number] = this.createDefaultSearchTimes();
    searchRanges = this.createSearchRanges();


    fetchData(page = 0, pageSize = 20) {
        this.meta.current = page;
        this.meta.pageSize = pageSize;
        this.loading = true;

        let promise = this.searchName != null ? this.search(page, pageSize) : this.fetch(page, pageSize);

        return promise.then(res => {
            this.data = res.data;
            this.meta = res.meta;
            this.loading = false;
        }).catch(res => {
            this.loading = false;
            return Promise.reject(res);
        });
    }

    abstract deleteItemImpl(id: string): Promise<any>;

    abstract fetchListImpl(page: number, size: number): Promise<{ meta: IPageMetaData; data: T[] }>;

    abstract searchImpl(name: string, startTime: number, endTime: number, page: number, size: number): Promise<{ meta: IPageMetaData; data: T[] }>;

    deleteItem(id: string) {
        return this.deleteItemImpl(id).then(res => {
            this.data = this.data.filter(item => item['id'] != id);
        });
    }

    private fetch(page: number = 0, pageSize: number = 20) {
        // TODO
        return this.search(page, pageSize);
    }

    private search(page: number = 0, pageSize: number = 20): Promise<any> {
        // TODO
        let [startTime, endTime] = !this.searchTimes
            ? ['', '']
            : this.searchTimes;
        return this.searchImpl(this.searchName || "", startTime as any, endTime as any, page, pageSize);
    }

    private createDefaultSearchTimes(): [number, number] {
        return [
            moment().subtract(1, 'month').unix() * 1000,
            moment().unix() * 1000
        ]
    }

    protected createSearchRanges() {
        return {
            '最近1天': [moment().subtract(1, 'day'), moment()],
            '最近1周': [moment().subtract(7, 'day'), moment()],
            '最近1个月': [moment().subtract(1, 'month'), moment()],
            '最近3个月': [moment().subtract(3, 'month'), moment()],
        }
    }

}